"""Storage service for file uploads."""
import os
import uuid
from typing import Optional
import oss2


class StorageService:
    """Service for storing files to OSS."""
    
    def __init__(
        self,
        endpoint: str,
        access_key_id: str,
        access_key_secret: str,
        bucket_name: str
    ):
        """Initialize storage service.
        
        Args:
            endpoint: OSS endpoint
            access_key_id: OSS access key ID
            access_key_secret: OSS access key secret
            bucket_name: OSS bucket name
        """
        self.endpoint = endpoint
        self.bucket_name = bucket_name
        
        # Initialize OSS auth and bucket
        auth = oss2.Auth(access_key_id, access_key_secret)
        self.bucket = oss2.Bucket(auth, endpoint, bucket_name)
    
    def upload_audio(
        self,
        audio_bytes: bytes,
        file_extension: str = "mp3",
        folder: str = "music"
    ) -> str:
        """Upload audio file to OSS.
        
        Args:
            audio_bytes: Audio file bytes
            file_extension: File extension (default: mp3)
            folder: Folder path in OSS (default: music)
            
        Returns:
            Public URL of uploaded file
            
        Raises:
            Exception: If upload fails
        """
        # Generate unique filename
        filename = f"{uuid.uuid4()}.{file_extension}"
        object_key = f"{folder}/{filename}"
        
        try:
            # Upload to OSS
            result = self.bucket.put_object(object_key, audio_bytes)
            
            if result.status == 200:
                # Return public URL
                return f"https://{self.bucket_name}.{self.endpoint}/{object_key}"
            else:
                raise Exception(f"OSS upload failed with status {result.status}")
                
        except Exception as e:
            raise Exception(f"Failed to upload audio to OSS: {e}")
    
    def delete_audio(self, object_key: str) -> bool:
        """Delete audio file from OSS.
        
        Args:
            object_key: Object key in OSS
            
        Returns:
            True if deletion successful
        """
        try:
            self.bucket.delete_object(object_key)
            return True
        except Exception:
            return False
